package com.shiguiwu.springmybatis.data;

import com.zaxxer.hikari.HikariDataSource;
import com.zaxxer.hikari.HikariPoolMXBean;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

/**
 * @description: 连接池监控
 * @author: stone
 * @date: Created by 2022/8/28 18:12
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.data
 */
@Component
@Slf4j
@EnableScheduling public class DataSourceMonitor {

    @Autowired
    private DataSource dataSource;

    //@Scheduled(fixedRate = 1000)
    public void monitor() {
        poolState((HikariDataSource) dataSource, true, "");
    }



    public static String poolState(HikariDataSource dataSource, boolean ifLog, String... prefix) {
        String poolName = dataSource.getPoolName();
        HikariPoolMXBean mx = dataSource.getHikariPoolMXBean();
        if (mx == null) {
            log.info("init ........... {}", dataSource.getPoolName());
            return "";
        }
        String format = String.format("%s - %sstats (total=%d, active=%d, idle=%d, waiting=%d)",
                poolName, (prefix.length > 0 ? prefix[0] : ""),
                mx.getTotalConnections(), mx.getActiveConnections(), mx.getIdleConnections(), mx.getThreadsAwaitingConnection());
        if (ifLog) {
            log.info("{}", format);
        }
        return format;
    }
}
